package com.iot08.admin.utils.buckettool;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @version 1.0
 * @Description: 阿里云oss上传
 * @author: Rock
 * @time: 2020/10/22 17:36
 */
@Slf4j
@Component
public class ALOSSUtil {

    @Value("${aliyun.oss.url}")
    private String url;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;


    //静态变量赋值 Component 和 set方法
    public static String DOMAIN;
    @Value("${aliyun.oss.domainurl}")
    public void setDOMAIN(String domain){
        DOMAIN = domain;
    }

    /**
     * 上传图片
     *
     * @param path
     * @param file
     * @time: 2020/10/22 17:59
     * @author: Rock
     * @version 1.0
     */
    public void upload(String path, MultipartFile file, int type) throws IOException {
        upload(path, file.getInputStream(), type);
    }

    public void upload(String path, InputStream inputStream, int type) throws IOException {
        // 取得上传文件
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(inputStream.available());
        // 可以在metadata中标记文件类型
        if (type == 1) {
            objectMetadata.setContentType(BaseBucketTool.IMG_CONTENT_TYPE);
        } else if (type == 2) {
            objectMetadata.setContentType(BaseBucketTool.AMR_CONTENT_TYPE);
        } else if (type == 3) {
            objectMetadata.setContentType(BaseBucketTool.ZIP_CONTENT_TYPE);
        } else if (type == 4) {
            objectMetadata.setContentType(BaseBucketTool.IMG_PNG_CONTENT_TYPE);
        }
//        else {
//            objectMetadata.setContentType(IMG_CONTENT_TYPE);
//        }
        // 创建OSSClient实例

        OSSClient ossClient = new OSSClient(url, accessKeyId, accessKeySecret);
//        ossClient.putObject(bucketName, path, inputStream, objectMetadata);
        ossClient.putObject(bucketName, path, inputStream);
        // 关闭client
        ossClient.shutdown();
        log.info("上传成功： " + path);
    }

    public void newUpload(String path, InputStream inputStream){
        try {
            String endpoint = "https://"+url;

            DefaultCredentials temp = new DefaultCredentials(accessKeyId, accessKeySecret, null);
            DefaultCredentialProvider credentialsProvider = new DefaultCredentialProvider(temp);

//            // 创建OSSClient实例。
//            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider, conf);
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

            try {
                // 创建PutObjectRequest对象。
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, inputStream);

                // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
                // ObjectMetadata metadata = new ObjectMetadata();
                // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
                // metadata.setObjectAcl(CannedAccessControlList.Private);
                // putObjectRequest.setMetadata(metadata);

                // 上传
                PutObjectResult result = ossClient.putObject(putObjectRequest);
                log.info("上传成功：{} result:{}",path, result);
            } catch (OSSException oe) {

                log.error("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                log.error("Error Message:" + oe.getErrorMessage());
                log.error("Error Code:" + oe.getErrorCode());
                log.error("Request ID:" + oe.getRequestId());
                log.error("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                log.error("ce:"+ce.getMessage(), ce);
                log.error("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                log.error("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        } catch (Exception e){
            log.error("错误:"+e.getMessage(), e);
        }
    }

    public boolean checkPath (String path){
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(url, accessKeyId, accessKeySecret);
        // 删除Object.
        boolean exist = ossClient.doesObjectExist(bucketName, path);
        // 关闭client
        ossClient.shutdown();

        return exist;
    }
    /**
     * @param filePath
     * @time: 2020/11/6 18:19
     * @author: Rock
     * @version 1.0
     */
    public Boolean delFile(String filePath) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(url, accessKeyId, accessKeySecret);
        try {
            // 删除Object.
            boolean exist = ossClient.doesObjectExist(bucketName, filePath);
            if (!exist) {
                log.info("文件不存在,filePath={}", filePath);
                return false;
            }
            log.info("删除文件,filePath={}", filePath);
            ossClient.deleteObject(bucketName, filePath);
        } catch (Exception e) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return true;
    }

    /**
     * @param objectName
     * @time: 2021/3/22 16:50
     * @author: Rock
     * @version 1.0
     */
    public ByteArrayOutputStream downloadFileStream(String objectName) {
        OSSClient ossClient = new OSSClient(url, accessKeyId, accessKeySecret);
        try {
            boolean exist = ossClient.doesObjectExist(bucketName, objectName);
            if (exist) {
                OSSObject object = ossClient.getObject(new GetObjectRequest(bucketName, objectName));
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = object.getObjectContent().read(buffer)) > -1) {
                    baos.write(buffer, 0, len);
                }
                baos.flush();
                return baos;
            }
        } catch (Exception e) {
            log.warn("downloadFileStream 异常。url={}", objectName);
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

}